package jssia.database.mysql.columns;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UnsignedBigIntColumn extends Column {

    private static final int LOWER = 0;
    private static final BigInteger UPPER = new BigInteger("18446744073709551615");

    public UnsignedBigIntColumn() {
    }

    public BigInteger get(ResultSet rs) throws SQLException {
        BigDecimal bigDecimal = rs.getBigDecimal(fullyQualifiedName);
        return bigDecimal == null ? null : bigDecimal.toBigInteger();
    }

    public void set(PreparedStatement ps, int index, long value) throws SQLException {
        if (value < LOWER)
            throw new IllegalArgumentException("Invalid value of " + value + ", must be greater than " + LOWER);
        ps.setLong(index, value);
    }

    public void set(PreparedStatement ps, int index, BigInteger value) throws SQLException {
        if (value.compareTo(BigInteger.ZERO) < 0 || value.compareTo(UPPER) > 0)
            throw new IllegalArgumentException("Invalid value of " + value + ", must be between " + LOWER + " and " + UPPER);
        ps.setObject(index, value);
    }
}
